import {concat, omit, path} from 'ramda'
import {compose, withState} from 'recompose'
import {DatePicker, Form, Input} from 'antd'
import {getDateTime} from '../util'
import moment from 'moment'
import Group from './Group'

const FormItem = Form.Item;

const _AntDatePicker = (props: object) => {

    const parseDate = (m: object) => {

        props.onChange(m._d + '')
        props.setState({value: m})
    }

    const value: string = props.value || '';
    const format = props.showTime ? "YYYY-MM-DD HH:mm" : "YYYY-MM-DD";

    return (
        <DatePicker {...omit(['required'], props)}
                    format={format}
                    value={props.state.value}
                    onChange={parseDate}
        />
    )
}

export const AntDatePicker = compose(
    withState('state', 'setState', props => ({
            value: props.value ? moment(getDateTime(props.value), 'YYYY-MM-DD HH:mm') : null
        })
    )
)(_AntDatePicker)


export const FormDatePicker = (props) => {

    const {labelCol, span, textAlign, getFieldValue,justify, label, matchName, placeholder, onChange, name, getFieldDecorator, initialValue, required, rules, width} = props;

    let commonRules = [];
    const matchNameCheck = (rule: object, value: string | number, callback: any) => {
        const matchV = new Date(getFieldValue(matchName.name));
        const flag = matchName.type == 'lg' ? new Date(value) <= matchV : new Date(value) > matchV;
        if (value && flag) {
            callback(matchName.message);
        } else {
            callback();
        }
    }
    if (matchName) {
        commonRules.push({
                validator: (rule: object, value: string | number, callback: any) => matchNameCheck(rule, value, callback)
            }
        )
    }

    return (
        <Group spans={[span || 16]} justify={justify || 'center'} textAligns={[textAlign || 'left']}>
            <FormItem
                labelCol={{span: labelCol || 0}}
                wrapperCol={{span: 24 - (labelCol || 0)}}
                label={label}
            >
                {getFieldDecorator(name, {
                    initialValue,
                    rules: concat([{required, message: '必填项'}], concat(rules || [], commonRules)),
                })(
                    <AntDatePicker {...props} style={{width: width || '100%'}}/>
                )}
            </FormItem>
        </Group>
    )
}